﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Giaiphongmatbang.BLL;
using Giaiphongmatbang.DataModel;
using System.Data;

namespace Giaiphongmatbang
{
    public partial class editObject : System.Web.UI.Page
    {
        #region variable
        public static DataTable tblLand;
        QLGPMBEntities db = new QLGPMBEntities();
        DataAccess.GPMBDataContext data = new DataAccess.GPMBDataContext();
        User user;
        int ProjectID
        {
            get { return (int)ViewState["ProjectID"]; }
            set { ViewState["ProjectID"] = value; }
        }
        int HouseHoldID
        {
            get { return (int)ViewState["HouseHoldID"]; }
            set { ViewState["HouseHoldID"] = value; }            
        }
        string CMND
        {
            get { return (string)ViewState["CMND"]; }
            set { ViewState["CMND"] = value; }
        }
        bool modeNew
        {
            get { return Convert.ToBoolean(hdfModeNew.Value); }
            set { hdfModeNew.Value = value.ToString(); }
        }
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            user = (User)Session["User"];
            if (!IsPostBack)
            {
                if (Session["User"] != null)
                {                    
                    if (!new UserRolesRepository().CheckRoles(user, (int)Utility.Enum.Roles.UpdateProject))
                    {
                        Response.Write("<script>alert('Bạn không đủ quyền để truy cập trang này!');window.location='/duan.aspx';</script>");                        
                        Response.Redirect("/duan.aspx");                        
                    }
                    ProjectID = int.Parse(Request.QueryString["pID"]);
                    HouseHoldID = int.Parse(Request.QueryString["hID"]);
                    HouseHold obj = db.HouseHolds.FirstOrDefault(p => p.HouseHoldID == HouseHoldID);
                    CMND = obj.CMND;
                    Title = "Cập nhật đối tượng : " + obj.FullName + " - Dự án: " + db.Projects.FirstOrDefault(p => p.ProjectID == ProjectID).ProjectName;
                    BindDataDropDown();
                    getValues();
                    BindDataRepeaterSuportOther();
                    Bindddl_LandType();
                    BuildtblLand();
                }               
                
            }
        }

        protected void getValues()
        {            
            Project project = new ProjectsRepository().GetByID(ProjectID);
            ltrProjectName.Text = project.ProjectName;
            ltrInvestor.Text = project.Investor;
            HouseHold household = new HouseHoldRepository().GetByID(HouseHoldID);
            Village village = new VillagesRepostory().GetByHouseHoldID(HouseHoldID);
            txtHouseHold.Text = household.FullName;
            drdGender.SelectedValue = household.Gender.ToString();
            txtPhoneNumber.Text = household.PhoneNumber;
            txtMemberCount.Text = household.MemberCount.ToString();
            txtAddress.Text = household.Address;
            drdVillage.SelectedValue = village.VillageID.ToString();
        }
        protected void BindDataDropDown()
        {
            drdVillage.DataSource = new VillagesRepostory().GetByDistrictID((int)Utility.Enum.DistrictCode.HungNguyen);
            drdVillage.DataValueField = "VillageID";
            drdVillage.DataTextField = "VillageName";
            drdVillage.DataBind();
        }

        protected void Bindddl_LandType()
        {
            DataAccess.GPMBDataContext datacontext = new DataAccess.GPMBDataContext();
            ddlLandType.DataSource = datacontext.uspGetAllLandType();
            ddlLandType.DataTextField = "LandName";
            ddlLandType.DataValueField = "LandID";
            ddlLandType.DataBind();
        }

        public void BuildtblLand()
        {
            tblLand = new DataTable();
            tblLand.Columns.Add("Index", typeof(int));
            tblLand.Columns.Add("LandID", typeof(int));
            tblLand.Columns.Add("LandName", typeof(string));
            tblLand.Columns.Add("Plot", typeof(string));
            tblLand.Columns.Add("ofMap", typeof(int));
            tblLand.Columns.Add("Place", typeof(string));
            tblLand.Columns.Add("Hamlet", typeof(string));
            tblLand.Columns.Add("Position", typeof(string));
            tblLand.Columns.Add("Areas", typeof(float));
            tblLand.Columns.Add("Unit", typeof(string));
            tblLand.Columns.Add("UnitPrice", typeof(float));
            tblLand.Columns.Add("Coefficient", typeof(float));
            tblLand.Columns.Add("UserAreas", typeof(float));
            tblLand.Columns.Add("toAmounts", typeof(float));
            tblLand.Columns.Add("Origin", typeof(string));
            tblLand.Columns.Add("Description", typeof(string));
            tblLand.Columns.Add("isNew", typeof(bool));

            DataAccess.GPMBDataContext datacontext = new DataAccess.GPMBDataContext();
            List<DataAccess.uspGetAllInventLandResult> listland = datacontext.uspGetAllInventLand(ProjectID, CMND).ToList();// store lấy inven land có projectid với cmnd test thì đúng

            if (listland != null)
            {
                foreach (DataAccess.uspGetAllInventLandResult item in listland)
                {
                    int index = tblLand.Rows.Count + 1;
                    tblLand.Rows.Add(index, item.LandID, item.LandName, item.Plot, item.ofMap, item.Place, item.Hamlet, item.Position, (float)item.Areas, item.Unit, (float)item.UnitPrice, (float)item.Coefficient, (float)item.UserAreas, (float)item.toAmounts, item.Origin, item.Description, true);
                }
            }
            rpt_LandDamage.DataSource = tblLand;
            rpt_LandDamage.DataBind();
        }

        #region Repeater InsertLand

        protected void btnAddLand_Click(object sender, EventArgs e)
        {
            int index = tblLand.Rows.Count + 1;
            int id = int.Parse(ddlLandType.SelectedValue);
            string landname = ddlLandType.SelectedItem.ToString();
            string plot = txtPlot.Text;
            int map = int.Parse(txtofMap.Text);
            string place = txtPlace.Text;
            string hamlet = txtHamlet.Text;
            string position = txtPosition.Text;
            float areas = float.Parse(txtAreas.Text);
            float unit = float.Parse(txtUnitPrice.Text);
            float userareas = float.Parse(txtUserAreas.Text);
            float toAmounts = areas * unit;
            string origin = txtOrigin.Text;
            string description = txtDescription.Text;
            bool isnew = false;
            DataAccess.GPMBDataContext datacontext = new DataAccess.GPMBDataContext();
            DataAccess.Land land = datacontext.uspGetLandByID(id).FirstOrDefault();
            float coefficient = (float)land.Coefficient;
            tblLand.Rows.Add(index, id, landname, plot, map, place, hamlet, position, areas, "m2", unit, coefficient, userareas, toAmounts, origin, description, isnew);
            rpt_LandDamage.DataSource = tblLand;
            rpt_LandDamage.DataBind();
        }

        protected void rpt_LandDamage_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            string command = e.CommandName;
            try
            {
                string index = e.CommandArgument.ToString();
                if (command.Equals("ibtnDelete"))
                {
                    int i = 0;
                    while (i < tblLand.Rows.Count)
                    {
                        DataRow dr = tblLand.Rows[i];
                        if (dr[0].ToString() == index)
                        {
                            if (bool.Parse(dr[16].ToString()) == true)
                            {
                                DataAccess.GPMBDataContext datacontext = new DataAccess.GPMBDataContext();
                                datacontext.uspDeleteInventLand(ProjectID, CMND, int.Parse(dr[1].ToString()), dr[3].ToString());
                            }
                            tblLand.Rows.Remove(dr);
                        }
                        i++;
                    }
                }
                rpt_LandDamage.DataSource = tblLand;
                rpt_LandDamage.DataBind();
            }
            catch { }
        }

        protected void btnInsertLand_Click(object sender, EventArgs e)
        {
            BindDataRepeaterInsertLand();
        }

        protected void BindDataRepeaterInsertLand()
        {
        }

        #endregion
        #region Repeater Insert Trees
        string imgTree(int id, bool expand)
        {
            if (!db.Trees.Any(p => p.ParentID == id))
                return "/Images/not.gif";
            if (db.Trees.Any(p => p.ParentID == id) && expand)
                return "/Images/plus.gif";
            return "/Images/minus.gif";
        }
        protected void btnInsertTree_Click(object sender, EventArgs e)
        {
            BindDataRepeaterInsertTree();
            btnInsertTree.Visible = false;
        }
        protected void BindDataRepeaterInsertTree()
        {
            rptInsertTree.DataSource = new TreesRepository().GetByParentID(0);
            rptInsertTree.DataBind();
        }

        protected void rptInsertTree_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer )
            {
                int ID = int.Parse(((HiddenField)e.Item.FindControl("hdf")).Value);
                ImageButton imgButton = (ImageButton)e.Item.FindControl("imgButton");
                TextBox txt = (TextBox)e.Item.FindControl("txtQuantity");
                CheckBox chk = (CheckBox)e.Item.FindControl("chk");
                if (new TreesRepository().HasChild(ID))
                {
                    txt.Visible = false;
                    chk.Visible = false;
                }
                imgButton.ImageUrl = imgTree(ID, true);
                imgButton.AlternateText = "   ";
                if (db.InventoryTrees.Any(p => p.ProjectID == ProjectID && p.CMND == CMND & p.TreeID == ID))
                {                    
                    chk.Checked = true;
                    txt.Text = db.InventoryTrees.FirstOrDefault(p => p.ProjectID == ProjectID && p.CMND == CMND & p.TreeID == ID).Quantity.ToString();
                }

            }
        }

        protected void imgButton1_Click(object sender, EventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            int ID = int.Parse(((HiddenField)btn.Parent.FindControl("hdf")).Value);
            HiddenField hdf = (HiddenField)btn.Parent.FindControl("hdfexpand");
            bool expand = Convert.ToBoolean(hdf.Value);
            Repeater rpt = btn.Parent.FindControl("rptInsertTree") as Repeater;
            btn.ImageUrl = imgTree(ID, !expand);
            if (expand == true)
            {
                hdf.Value = "false";
                rpt.DataSource = new TreesRepository().GetByParentID(ID);
            }
            else
            {
                hdf.Value = "true";
                rpt.DataSource = null;
            }
            rpt.DataBind();
        }
        #endregion
        #region Repeater Insert House
        string imgHouse(int id, bool expand)
        {
            if (!db.HouseTypes.Any(p => p.ParentID == id))
                return "/Images/not.gif";
            if (db.HouseTypes.Any(p => p.ParentID == id) && expand == true)
                return "/Images/plus.gif";
            return "/Images/minus.gif";
        }
        protected void btnInsertHouse_Click(object sender, EventArgs e)
        {
            BindDataRepeaterInsertHouse();
            btnInsertHouse.Visible = false;
        }
        protected void BindDataRepeaterInsertHouse()
        {
            rptInsertHouse.DataSource = new HouseTypesRepository().GetByParentID(0);
            rptInsertHouse.DataBind();
        }

        protected void rptInsertHouse_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Footer && e.Item.ItemType != ListItemType.Header)
            {
                int ID = int.Parse(((HiddenField)e.Item.FindControl("hdf")).Value);
                ImageButton imgButton = (ImageButton)e.Item.FindControl("imgButton");
                TextBox txt = (TextBox)e.Item.FindControl("txtQuantity");
                CheckBox chk = (CheckBox)e.Item.FindControl("chk");
                if (new HouseTypesRepository().HasChild(ID))
                {
                    txt.Visible = false;
                    chk.Visible = false;
                }
                imgButton.ImageUrl = imgHouse(ID, true);
                imgButton.AlternateText = "   ";
                if (db.InventoryHouses.Any(p => p.ProjectID == ProjectID && p.CMND == CMND & p.HouseID == ID))
                {
                    chk.Checked = true;
                    txt.Text = db.InventoryHouses.FirstOrDefault(p => p.ProjectID == ProjectID && p.CMND == CMND & p.HouseID == ID).Quantity.ToString();
                }
            }
        }

        protected void imgButton2_Click(object sender, EventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            int ID = int.Parse(((HiddenField)btn.Parent.FindControl("hdf")).Value);
            HiddenField hdf = (HiddenField)btn.Parent.FindControl("hdfexpand");
            bool expand = Convert.ToBoolean(hdf.Value);
            Repeater rpt = btn.Parent.FindControl("rptInsertHouse") as Repeater;
            btn.ImageUrl = imgHouse(ID, !expand);
            if (expand == true)
            {
                hdf.Value = "false";
                rpt.DataSource = new HouseTypesRepository().GetByParentID(ID);
            }
            else
            {
                hdf.Value = "true";
                rpt.DataSource = null;
            }
            rpt.DataBind();
        }
        #endregion
        #region Repeater Insert Building
        string imgBuilding(int id, bool expand)
        {
            if (!db.Buildings.Any(p => p.ParentID == id))
                return "/Images/not.gif";
            if (db.Buildings.Any(p => p.ParentID == id) && expand == true)
                return "/Images/plus.gif";
            return "/Images/minus.gif";
        }
        protected void btnInsertBuilding_Click(object sender, EventArgs e)
        {
            BindDataRepeaterInsertBuilding();
            btnInsertBuilding.Visible = false;
        }
        protected void BindDataRepeaterInsertBuilding()
        {
            rptInsertBuilding.DataSource = new BuildingsRepository().GetByParentID(0);
            rptInsertBuilding.DataBind();
        }

        protected void rptInsertBuilding_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Footer && e.Item.ItemType != ListItemType.Header)
            {
                int ID = int.Parse(((HiddenField)e.Item.FindControl("hdf")).Value);
                ImageButton imgButton = (ImageButton)e.Item.FindControl("imgButton");
                TextBox txt = (TextBox)e.Item.FindControl("txtQuantity");
                TextBox txtRemaining = (TextBox)e.Item.FindControl("txtRemainingPercent");
                CheckBox chk = (CheckBox)e.Item.FindControl("chk");
                if (new BuildingsRepository().HasChild(ID))
                {
                    txtRemaining.Visible = false;
                    txt.Visible = false;
                    chk.Visible = false;
                }
                imgButton.ImageUrl = imgBuilding(ID, true);
                imgButton.AlternateText = "   ";
                if (db.InventoryBuildings.Any(p => p.ProjectID == ProjectID && p.CMND == CMND & p.BuildingID == ID))
                {
                    chk.Checked = true;
                    txt.Text = db.InventoryBuildings.FirstOrDefault(p => p.ProjectID == ProjectID && p.CMND == CMND & p.BuildingID == ID).Quantity.ToString();
                }
            }
        }

        protected void imgButton3_Click(object sender, EventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            int ID = int.Parse(((HiddenField)btn.Parent.FindControl("hdf")).Value);
            HiddenField hdf = (HiddenField)btn.Parent.FindControl("hdfexpand");
            bool expand = Convert.ToBoolean(hdf.Value);
            Repeater rpt = btn.Parent.FindControl("rptInsertBuilding") as Repeater;
            btn.ImageUrl = imgBuilding(ID, !expand);
            if (expand == true)
            {
                hdf.Value = "false";
                rpt.DataSource = new BuildingsRepository().GetByParentID(ID);
            }
            else
            {
                hdf.Value = "true";
                rpt.DataSource = null;
            }
            rpt.DataBind();
        }
        #endregion
        #region Repeater Insert Graves
        string imgGrave(int id, bool expand)
        {
            if (!db.Graves.Any(p => p.ParentID == id))
                return "/Images/not.gif";
            if (db.Graves.Any(p => p.ParentID == id) && expand == true)
                return "/Images/plus.gif";
            return "/Images/minus.gif";
        }
        protected void btnInsertGrave_Click(object sender, EventArgs e)
        {
            BindDataRepeaterInsertGrave();
            btnInsertGrave.Visible = false;
        }
        protected void BindDataRepeaterInsertGrave()
        {
            rptInsertGrave.DataSource = new GravesRepository().GetByParentID(0);
            rptInsertGrave.DataBind();
        }

        protected void rptInsertGrave_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Footer && e.Item.ItemType != ListItemType.Header)
            {
                int ID = int.Parse(((HiddenField)e.Item.FindControl("hdf")).Value);
                ImageButton imgButton = (ImageButton)e.Item.FindControl("imgButton");
                TextBox txt = (TextBox)e.Item.FindControl("txtQuantity");
                CheckBox chk = (CheckBox)e.Item.FindControl("chk");
                if (new GravesRepository().HasChild(ID))
                {
                    txt.Visible = false;
                    chk.Visible = false;
                }
                imgButton.ImageUrl = imgGrave(ID, true);
                imgButton.AlternateText = "   ";
                if (db.InventoryGraves.Any(p => p.ProjectID == ProjectID && p.CMND == CMND & p.GraveID == ID))
                {
                    chk.Checked = true;
                    txt.Text = db.InventoryGraves.FirstOrDefault(p => p.ProjectID == ProjectID && p.CMND == CMND & p.GraveID == ID).Quantity.ToString();
                }
            }
        }

        protected void imgButton4_Click(object sender, EventArgs e)
        {
            ImageButton btn = (ImageButton)sender;
            int ID = int.Parse(((HiddenField)btn.Parent.FindControl("hdf")).Value);
            HiddenField hdf = (HiddenField)btn.Parent.FindControl("hdfexpand");
            bool expand = Convert.ToBoolean(hdf.Value);
            Repeater rpt = btn.Parent.FindControl("rptInsertGrave") as Repeater;
            btn.ImageUrl = imgGrave(ID, !expand);
            if (expand == true)
            {
                hdf.Value = "false";
                rpt.DataSource = new GravesRepository().GetByParentID(ID);
            }
            else
            {
                hdf.Value = "true";
                rpt.DataSource = null;
            }
            rpt.DataBind();
        }
        #endregion
        #region Repeater SupportOther
        SupportOtherRepository spOther = new SupportOtherRepository();
        protected void BindDataRepeaterSuportOther()
        {
            var datasource = spOther.GetByProjectIDAndCMND(ProjectID, CMND);
            rptSuppportOther.DataSource = datasource;
            rptSuppportOther.DataBind();
        }
        int ID
        {
            get { return (int)ViewState["ID"]; }
            set { ViewState["ID"] = value; }
        }
        protected void rptSuppportOther_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            ID = int.Parse(e.CommandArgument.ToString());
            if (e.CommandName.Equals("btnEdit"))
            {
                SupportOther entity = spOther.GetByID(ID);
                txtSupportName.Text = entity.SupportName;
                txtPrice.Text = entity.UnitPrice.ToString();
                modeNew = false;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "showdialog();", true);
            }
            else if (e.CommandName.Equals("btnDelete"))
            {
                spOther.Delete(ID);
                BindDataRepeaterSuportOther();
            }
        }
        //protected void btnInsert_Click(object sender, EventArgs e)
        //{
        //    txtSupportName.Text = string.Empty;
        //    txtPrice.Text = string.Empty;
        //    modeNew = true;
        //    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "showdialog();", true);
        //}
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (modeNew)
            {
                Support support = db.Supports.FirstOrDefault(p => p.CMND.Equals(CMND) && p.ProjectID == ProjectID);
                if (support == null)
                {
                    support = new Support
                    {
                        CMND = CMND,
                        ProjectID = ProjectID
                    };
                    db.AddToSupports(support);
                    db.SaveChanges();
                }
                SupportOther sp = new SupportOther
                {
                    Support = db.Supports.FirstOrDefault(p=>p.CMND.Equals(CMND) && p.ProjectID==ProjectID),
                    SupportName = txtSupportName.Text.Trim(),
                    UnitPrice = decimal.Parse(txtPrice.Text.Trim())
                };
                db.SaveChanges();
                BindDataRepeaterSuportOther();
            }
            else
            {
                SupportOther sp = db.SupportOthers.FirstOrDefault(p => p.SupportOtherID == ID);
                sp.SupportName = txtSupportName.Text.Trim();
                sp.UnitPrice = decimal.Parse(txtPrice.Text.Trim());
                db.SaveChanges();
                BindDataRepeaterSuportOther();
            }
        }       

        #endregion
        #region Command
        protected void btnInsertSupportMove_Click(object sender, EventArgs e)
        {
            btnInsertSupportMove.Visible = false;
            ucSupportMove1.Visible = true;
            ucSupportMove1.BindData();
        }

        protected void btnInsertSupportRent_Click(object sender, EventArgs e)
        {
            btnInsertSupportRent.Visible = false;
            ucSupportRent1.Visible = true;
            ucSupportRent1.BindData();
        }

        protected void btnInsertSupportStabilize_Click(object sender, EventArgs e)
        {
            btnSupportStabilize.Visible = false;
            ucSupportStabilize1.Visible = true;
            ucSupportStabilize1.BindData();
        }

        protected void btnInsertSupportJob_Click(object sender, EventArgs e)
        {
            btnSupportJob.Visible = false;
            ucSupportJob1.Visible = true;
            ucSupportJob1.BindData();
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Session["ProjectID"] = ProjectID;
            Response.Redirect("/duan.aspx");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="CMND"></param>
        /// <param name="landID"></param>
        /// <param name="plot"></param>
        /// <param name="ofMap"></param>
        /// <param name="place"></param>
        /// <param name="hamlet"></param>
        /// <param name="position"></param>
        /// <param name="areas"></param>
        /// <param name="unit"></param>
        /// <param name="unitprice"></param>
        /// <param name="userareas"></param>
        /// <param name="origin"></param>
        /// <param name="description"></param>
        protected void AddInventoryLand(int projectid, string CMND, int landID, string plot, int ofMap, string place, string hamlet, string position, float areas, string unit, float unitprice, float userareas, string origin, string description)
        {
            try
            {
                DataAccess.GPMBDataContext datacontext = new DataAccess.GPMBDataContext();
                DataAccess.Land land = datacontext.uspGetLandByID(landID).FirstOrDefault();
                datacontext.uspInsertInvenLand(projectid, CMND, landID, plot, ofMap, place, hamlet, position, areas, unit, unitprice, land.Coefficient, userareas, land.isSupport, unitprice * areas, origin, description);
            }
            catch { }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            int VillageID = int.Parse(drdVillage.SelectedValue);
            data.uspHouseHoldUpdate(HouseHoldID, CMND, txtHouseHold.Text, txtAddress.Text, Convert.ToBoolean(drdGender.SelectedValue),
                                    txtPhoneNumber.Text, int.Parse("0"+txtMemberCount.Text), int.Parse(drdVillage.SelectedValue));

            string[] split = new string[] { "|$--$|" };
            string[] separator = new string[] { "$--$" };

            for (int i = 0; i < tblLand.Rows.Count; i++)
            {
                bool isnew = bool.Parse(tblLand.Rows[i][16].ToString());
                if (!isnew)
                {
                    int landid = int.Parse(tblLand.Rows[i][1].ToString());
                    string plot = tblLand.Rows[i][3].ToString();
                    int ofmap = int.Parse(tblLand.Rows[i][4].ToString());
                    string place = tblLand.Rows[i][5].ToString();
                    string hamlet = tblLand.Rows[i][6].ToString();
                    string position = tblLand.Rows[i][7].ToString();
                    float areas = float.Parse(tblLand.Rows[i][8].ToString());
                    string unit = tblLand.Rows[i][9].ToString();
                    float unitprice = float.Parse(tblLand.Rows[i][10].ToString());
                    float coefficient = float.Parse(tblLand.Rows[i][11].ToString());
                    float userareas = float.Parse(tblLand.Rows[i][12].ToString());
                    float toamounts = float.Parse(tblLand.Rows[i][13].ToString());
                    string origin = tblLand.Rows[i][14].ToString();
                    string description = tblLand.Rows[i][15].ToString();
                    AddInventoryLand(ProjectID, CMND, landid, plot, ofmap, place, hamlet, position, areas, unit, unitprice, userareas, origin, description);
                }
            }

            string[] arrTree = hdfTree.Value.Split(split, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in arrTree)
            {
                string[] value = item.Split(separator, StringSplitOptions.None);
                int ID = int.Parse(value[0]);
                double values = 0; double.TryParse(value[1],out values);
                InventoryTree objInvent;
                if (!db.InventoryTrees.Any(p => p.CMND == CMND && p.ProjectID == ProjectID && p.TreeID == ID))
                {
                    objInvent = new InventoryTree
                    {
                        Inventory = db.Inventories.FirstOrDefault(p => p.ProjectID == ProjectID && p.CMND == CMND),
                        Tree = db.Trees.FirstOrDefault(p => p.TreeID == ID),
                        Quantity = values
                    };
                }
                else
                {
                    objInvent = db.InventoryTrees.FirstOrDefault(p => p.CMND == CMND && p.ProjectID == ProjectID && p.TreeID == ID);
                    if (values == 0)
                    {
                        db.DeleteObject(objInvent);
                    }
                    else
                    {
                        objInvent.Quantity = values;
                    }
                }
                db.SaveChanges();
            }

            string[] arrHouse = hdfHouse.Value.Split(split, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in arrHouse)
            {
                string[] value = item.Split(separator, StringSplitOptions.None);
                int ID = int.Parse(value[0]);
                double values = 0; double.TryParse(value[1],out values);
                InventoryHouse objInvent;
                if (!db.InventoryHouses.Any(p => p.CMND == CMND && p.ProjectID == ProjectID && p.HouseID == ID))
                {
                    objInvent = new InventoryHouse
                    {
                        Inventory = db.Inventories.FirstOrDefault(p => p.ProjectID == ProjectID && p.CMND == CMND),
                        HouseType = db.HouseTypes.FirstOrDefault(p => p.HouseID == ID),
                        Quantity = values
                    };
                }
                else
                {
                    objInvent = db.InventoryHouses.FirstOrDefault(p => p.CMND == CMND && p.ProjectID == ProjectID && p.HouseID == ID);
                    if (values == 0)
                    {
                        db.DeleteObject(objInvent);
                    }
                    else
                    {
                        objInvent.Quantity = values;
                    }
                }
                db.SaveChanges();
            }

            string[] arrBuilding = hdfBuilding.Value.Split(split, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in arrBuilding)
            {
                string[] value = item.Split(separator, StringSplitOptions.None);
                int ID = int.Parse(value[0]);
                double values = 0; double.TryParse(value[1],out values);
                double remaining = 0; double.TryParse(value[2], out remaining);
                InventoryBuilding objInvent;
                if (!db.InventoryBuildings.Any(p => p.CMND == CMND && p.ProjectID == ProjectID && p.BuildingID == ID))
                {
                    objInvent = new InventoryBuilding
                    {
                        Inventory = db.Inventories.FirstOrDefault(p => p.ProjectID == ProjectID && p.CMND == CMND),
                        Building = db.Buildings.FirstOrDefault(p => p.BuildingID == ID),
                        Quantity = values,
                        RemainingPercent = remaining
                    };
                }
                else
                {
                    objInvent = db.InventoryBuildings.FirstOrDefault(p => p.CMND == CMND && p.ProjectID == ProjectID && p.BuildingID == ID);
                    if (values == 0)
                    {
                        db.DeleteObject(objInvent);
                    }
                    else
                    {
                        objInvent.Quantity = values;
                        objInvent.RemainingPercent = remaining;
                    }
                }
                db.SaveChanges();
            }

            string[] arrGrave = hdfGrave.Value.Split(split, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in arrGrave)
            {
                string[] value = item.Split(separator, StringSplitOptions.None);
                int ID = int.Parse(value[0]);
                double values = 0; double.TryParse(value[1],out values);
                InventoryGrave objInvent;
                if (!db.InventoryGraves.Any(p => p.CMND == CMND && p.ProjectID == ProjectID && p.GraveID == ID))
                {
                    objInvent = new InventoryGrave
                    {
                        Inventory = db.Inventories.FirstOrDefault(p => p.ProjectID == ProjectID && p.CMND == CMND),
                        Grave = db.Graves.FirstOrDefault(p => p.GraveID == ID),
                        Quantity = values
                    };
                }
                else
                {
                    objInvent = db.InventoryGraves.FirstOrDefault(p => p.CMND == CMND && p.ProjectID == ProjectID && p.GraveID == ID);
                    if (values == 0)
                    {
                        db.DeleteObject(objInvent);
                    }
                    else
                    {
                        objInvent.Quantity = values;
                    }
                }
                db.SaveChanges();
            }

            Support support = db.Supports.FirstOrDefault(p => p.ProjectID == ProjectID && p.HouseHold.HouseHoldID == HouseHoldID);
            if (support == null)
            {
                support = new Support
                {
                    ProjectID = ProjectID,
                    CMND = CMND,
                    HouseHold = db.HouseHolds.FirstOrDefault(p=>p.CMND.Equals(CMND)),
                    Project = db.Projects.FirstOrDefault(p=>p.ProjectID == ProjectID)
                };
                db.AddToSupports(support);
                db.SaveChanges();
                support = db.Supports.FirstOrDefault(p => p.ProjectID == ProjectID && p.HouseHold.HouseHoldID == HouseHoldID);
            }
            int? SupportMoveID = null;
            try { SupportMoveID = int.Parse(hdfSupportMove.Value); }
            catch { }
            int? SupportRentID = null;
            int? QuantityRent = null;
            try
            {
                string[] value = hdfSupportRent.Value.Split(separator, StringSplitOptions.None);
                SupportRentID = int.Parse(value[0]);
                QuantityRent = int.Parse(value[1]);
            }
            catch { };
            int? SupportStabilizeID = null;
            int? QuantityStabilize = null;
            try
            {
                string[] value = hdfSupportStabilize.Value.Split(separator, StringSplitOptions.None);
                SupportStabilizeID = int.Parse(value[0]);
                QuantityStabilize = int.Parse(value[1]);
            }
            catch { }
            int? SupportJobID = null;
            try
            {
                SupportJobID = int.Parse(hdfSupportJob.Value);
            }
            catch { }
            if (SupportMoveID.HasValue)
            {
                support.SupportMove = db.SupportMoves.FirstOrDefault(p => p.SupportMoveID == SupportMoveID.Value);
            }
            if (SupportRentID.HasValue)
            {
                support.SupportRent = db.SupportRents.FirstOrDefault(p => p.SupporRenttID == SupportRentID.Value);
                support.QuantityRent = QuantityRent.Value;
            }
            if (SupportStabilizeID.HasValue)
            {
                support.SupportStabilize = db.SupportStabilizes.FirstOrDefault(p => p.SupportStabilizeID == SupportStabilizeID.Value);
                support.QuantityStabilize = QuantityStabilize.Value;
            }
            if (SupportJobID.HasValue)
            {
                support.SupportJob = db.SupportJobs.FirstOrDefault(p => p.SuportJobID == SupportJobID.Value);
            }
            db.SaveChanges();
            Session["ProjectID"] = ProjectID;
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Cập nhật thành công!'); window.location='duan.aspx';", true);
        }
        #endregion


    }
}